<template>
  <div ref="chart" :style="{ width: '100%', height: '312px' }"></div>
</template>

<script>
export default {
  name: 'GraphECharts',
  props: {
    options: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      chart: null,
      baseOptions: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985',
            },
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '6%',
          containLabel: true,
        },
        dataZoom: [
          {
            type: 'slider',
            show: true,
            xAxisIndex: [0],
            start: 0,
            end: 100,
            height: 10,
            bottom: 5,
            fillerColor: '#ccc',
            borderColor: '#ccc',
          },
          {
            type: 'inside',
            xAxisIndex: [0],
            start: 0,
            end: 100,
          },
        ],
      },
    };
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    initChart() {
      this.chart = this.$echarts.init(this.$refs.chart);
      this.chart.setOption({ ...this.options, ...this.baseOptions });
    },
  },
  watch: {
    options: {
      deep: true,
      handler(newOptions) {
        // if (this.chart) {
        //   this.chart.setOption({ ...newOptions, ...this.baseOptions });
        // }
        const dataLength = newOptions?.xAxis?.data.length;
        if (dataLength > 7) {
          const start = ((dataLength - 7) / dataLength) * 100;
          const end = 100;
          this.chart.setOption({
            ...newOptions,
            ...this.baseOptions,
            dataZoom: [
              {
                ...this.baseOptions.dataZoom[0],
                start,
                end,
              },
              {
                ...this.baseOptions.dataZoom[1],
                start,
                end,
              },
            ],
          });
        } else {
          this.chart.setOption({ ...newOptions, ...this.baseOptions });
        }
      },
      // immediate: true,
    },
  },
};
</script>
